<?php
include_once  "../lib/databases.php";
include_once "../lib/function.php";
//接收数据
$data = isset($_POST['data']) ? $_POST['data'] : "";

//判断上传的数据是否完整
if($data == ""){
    echo $this->error("请输入登录信息");
}else{
    //判断验证码是否正确
    if(strtolower($data["captcha"]) != strtolower($_SESSION['captcha_code'])){
        echo $fun->error("验证码有误");
    }else{
        $username = $data["username"];
        $password = md5($data["password"]);
        //判断登录是否成功
        $res = $db->getOneData("select id,name,picture,email,phone from user where name = '{$username}' and password='{$password}'");
        if($res){
            //登录成功
            $_SESSION["user_info"] = $res;
            //追加登录日志
            $db->insertLog($res['id'],$res['name'],"login","登录");
            //处理“记住我”功能
            if(isset($data['remember'])){
                if (isset($_POST['remember'])) {
                    // 生成安全的令牌
                    $token = bin2hex(random_bytes(32));
                    $expires = time() + 30 * 24 * 60 * 60; // 30天有效期
                    // 设置持久化cookie
                    setcookie('remember_token', $token, $expires, '/', '', true, true);
                    setcookie('userid', $res['id'], $expires, '/', '', true, true);
                }
            }
            //返回信息
            echo $fun->success("登录成功");
        }else{
            //登录失败
            echo $fun->error("登录失败，用户名或密码错误。");
        }
    }
}
?>